<template>
    <el-container style="height: 700px; border: 1px solid #eee">

        <!--侧边栏-->
        <component-sidebar></component-sidebar>

        <el-container>
            <!--标题-->
            <el-header style="text-align: right; font-size: 12px">
                <h1 id="pageTitle">图书管理系统</h1>
            </el-header>

            <el-main>
                <!--搜索表单-->
                <el-form id="categorySearchForm" :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="书名：">
                        <el-input v-model="formInline.bookName" placeholder="书名"></el-input>
                    </el-form-item>
                    <el-form-item label="作者：">
                        <el-input v-model="formInline.author" placeholder="作者"></el-input>
                    </el-form-item>
                    <el-form-item label="出版社：">
                        <el-input v-model="formInline.publishingHouse" placeholder="出版社"></el-input>
                    </el-form-item>
                    <el-form-item label="库存">
                        <el-select v-model="formInline.hasRepertory" placeholder="是否有库存">
                            <el-option label="是" value="1"></el-option>
                            <el-option label="否" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchCategory">查询</el-button>
                    </el-form-item>
                    <el-button id="insertBtn" type="primary" icon="el-icon-plus" circle
                               @click="dialogFormVisible = true">
                    </el-button>
                </el-form>
                <!--数据表格-->
                <el-table
                        :data="tableData"
                        border
                        style="width: 100%"
                        align="center"
                        id="table">
                    <el-table-column
                            prop="id"
                            label="图书分类编号"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="bookName"
                            label="书名"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="author"
                            label="作者"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="publishingHouse"
                            label="出版社"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="repertory"
                            label="库存"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="updateTime"
                            label="最近更新时间"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            align="center">
                        <template slot-scope="scope">
                            <el-button @click="clickLook(scope.row)" type="text" size="small">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!--分页条-->
                <div class="block">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pageNation.currentPage"
                            :page-sizes="[5, 10, 20, 30]"
                            :page-size="pageNation.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="pageNation.total">
                    </el-pagination>
                </div>
                <!--图书入库弹窗-->
                <el-dialog title="图书入库" :visible.sync="dialogFormVisible">
                    <el-form :model="addBookForm">

                        <el-form-item label="书名:"
                                      prop="name">
                            <el-input v-model="addBookForm.name"
                                      placeholder="请填写书名"
                                      maxlength="20"/>
                        </el-form-item>
                        <el-form-item label="作者:"
                                      prop="author">
                            <el-input v-model="addBookForm.author"
                                      placeholder="请填写作者"
                                      maxlength="20"/>
                        </el-form-item>

                        <el-form-item label="出版社:"
                                      prop="publishingHouse">
                            <el-input v-model="addBookForm.publishingHouse"
                                      placeholder="请填写出版社"/>
                        </el-form-item>

                        <el-form-item label="价格:"
                                      prop="price">
                            <el-input v-model="addBookForm.price"
                                      placeholder="请填写价格"/>
                        </el-form-item>

                        <el-form-item label="图书封面">
                            <el-upload
                                    class="cover-uploader"
                                    action="/common/admin/common/upload"
                                    :headers="uploadHeaders"
                                    name="file"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload"
                            >
                                <img v-if="addBookForm.cover" :src="addBookForm.cover" class="cover" alt=""/>
                                <i v-else class="el-icon-plus cover-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>

                        <el-form-item align="center">
                            <el-button type="primary" @click="insertBookWithCategory">提交</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
            </el-main>
        </el-container>
    </el-container>
</template>


<style>
.el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
}

#pageTitle {
    margin: 0;
    font-size: 40px;
    text-align: center;
}

#insertBtn {
    display: flex;
    float: right;
}

.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.cover {
    width: 100px;
    height: 100px;
    display: block;
}

.cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.cover-uploader .el-upload:hover {
    border-color: #409eff;
}

</style>

<script>
import axios from "axios";
import ComponentSidebar from "@/components/ComponentSidebar.vue";

const sendRequestMethod = {
    //发请求查询图书分类
    listCategory(pageNation, formInline) {
        try {
            let url = "/category/admin/category/list";
            url += ("?page=" + pageNation.currentPage + "&pageSize=" + pageNation.pageSize);

            if (formInline.bookName != null) {
                url += "&bookName=" + formInline.bookName;
            }
            if (formInline.author != null) {
                url += "&author=" + formInline.author;
            }
            if (formInline.publishingHouse != null) {
                url += "&publishingHouse=" + formInline.publishingHouse;
            }
            if (formInline.hasRepertory != null) {
                url += "&hasRepertory=" + formInline.hasRepertory;
            }
            axios.get(url, {
                headers: {
                    'token': sessionStorage.getItem("token")
                }
            }).then(
                    (res) => {
                        this.tableData = res.data.data.records;
                        this.pageNation.total = res.data.data.total;
                    }
            ).catch(
                    () => {
                        //this.openNotification("error", "错误", "查询图书分类异常，可能是服务器异常");
                        //跳转登录页面
                        this.$router.push("/login");
                    }
            );
        } catch (error) {
            // 捕获OS错误或其他异常
            //console.error('Caught an error:', error);
            this.openNotification("error", "错误", "查询图书分类");
        }
    },
}

export default {
    components: {ComponentSidebar},
    data() {
        const item = {
            id: '',
            cover: "",
            bookName: '',
            author: '',
            publishingHouse: '',
            repertory: null,
            updateTime: ''
        };
        return {
            //上传请求头
            uploadHeaders: {
                'token': sessionStorage.getItem("token"),
            },

            // 表格数据
            tableData: Array(0).fill(item),
            // 搜索表单数据
            formInline: {
                bookName: null,
                author: null,
                publishingHouse: null,
                hasRepertory: null,
            },
            //分页条属性
            pageNation: {
                currentPage: 1,
                pageSize: 5,
                total: 0
            },
            // 图书入库弹窗
            dialogTableVisible: false,
            dialogFormVisible: false,
            // 图书入库弹窗表单数据
            addBookForm: {
                name: '',
                author: '',
                publishingHouse: '',
                cover: '',
                price: '',
                enableLend: -1,
            },
            formLabelWidth: '120px',
            imageUrl: '',
        }
    },


    methods: {
        ...sendRequestMethod,

        //点击查询按钮
        searchCategory() {
            this.listCategory(this.pageNation, this.formInline);
        },

        //分页条pageSize改变
        handleSizeChange(val) {
            this.pageNation.pageSize = val;
            this.listCategory(this.pageNation, this.formInline);
        },

        //分页条currentPage改变
        handleCurrentChange(val) {
            this.pageNation.currentPage = val;
            this.listCategory(this.pageNation, this.formInline);
        },

        //弹出通知
        openNotification(type, title, message) {
            if (type === "error") {
                this.$notify.error({
                    title: title,
                    message: message
                });
            }

            if (type === "info") {
                this.$notify.info({
                    title: title,
                    message: message
                });
            }

            if (type === "warning") {
                this.$notify.warning({
                    title: title,
                    message: message
                });
            }

            if (type === "success") {
                this.$notify.success({
                    title: title,
                    message: message
                });
            }


        },

        //图片上传前回调
        beforeAvatarUpload() {

        },

        //图片提交成功回调
        handleAvatarSuccess(res) {
            //console.log("图片上传成功" + res.data);
            this.imageUrl = res.data;
            this.addBookForm.cover = res.data;
        },

        //图书入库（同时新增分类）
        insertBookWithCategory() {
            let url = "/book/admin/book";
            axios.post(url, this.addBookForm, {
                headers: {
                    'token': sessionStorage.getItem("token"),
                    'Content-Type': 'application/json'
                }
            }).then(
                    () => {
                        this.openNotification("success", "成功", "新增图书成功：《" + this.addBookForm.name + "》");
                        this.dialogFormVisible = false;
                        this.listCategory(this.pageNation, this.formInline);
                    }
            ).catch(
                    (err) => {
                        console.error(err);
                        this.openNotification("error", "错误", "新增图书失败");
                    }
            );
        },

        //查看图书详情
        clickLook(row) {
            //console.log(row.id);
            //跳转到图书界面，并传递id
            sessionStorage.setItem("categoryId", row.id);
            this.$router.push({path: '/book'});
        }
    },

    mounted() {
        try {
            this.listCategory(this.pageNation, this.formInline);
        } catch (e) {
            console.error(e);
            this.openNotification("error", "错误", "前端错误")
        }
    }
};
</script>
